/*!
 * Vertical Parallax JavaScript Library v0.1
 * https://code.google.com/p/vertical-parallax
 *
 * Copyright 2014
 * Released under the MIT license
 *
 * Date: 2014-03-13T01:25Z
 */
function vparallax(elementHeight, inertia, scrollCallback) {
	this.bgElemIndex = [];
	this.bgs = [];
	this.elementHeight = elementHeight;
	this.inertia = inertia;
	this.scrollCallback = scrollCallback;
	var hasTouch = 'ontouchstart' in window;
	
	jQuery.each(jQuery('.parallax_element'), function(index, value) {
		value.style.height = elementHeight + 'px';
		if (jQuery(value).find('.parallax_bg').length != 0) {
			bgElemIndex.push(index);
		}
		if(hasTouch){
			value.style.position = 'absolute';
			value.style.top = (index * elementHeight) + 'px';
		}
	});

	aux = jQuery('.parallax_bg');
	for (var i = 0; i < aux.length; i++) {
		aux[i].style.top = bgElemIndex[i] * elementHeight;
		bgs.push(jQuery(aux[i]));
	}
	
	var scrollTo = function(value) {
		var scroll = typeof value == 'object' ? jQuery(this).scrollTop() : value;
		if (scroll >= 0) {
			for (var index = 0; index < bgs.length; index++) {
				var magicNumber = (scroll - (bgElemIndex[index] * elementHeight));
				bgs[index].css('backgroundPosition', 'center ' + parseInt(magicNumber * inertia * -1) + 'px');
			}
			if (scrollCallback != null) {
				scrollCallback(scroll);
			}
		}
	};

	if(hasTouch){
		var backupY = null;
		var topFactor = null;
		
		jQuery('#parallax_container').addClass('parallax_container_mobile');
		jQuery('#parallax_container').bind('mousedown touchstart', function(event){
			event.preventDefault();
			event = event.originalEvent.touches[0];
			backupY = event.clientY;
			topFactor = parseInt(jQuery('.parallax_element')[0].style.top.replace("px", ''));
		});
		jQuery('#parallax_container').bind('mousemove touchmove', function(event){
			event.preventDefault();
			event = event.originalEvent.touches[0];
			if(backupY != null){
				var movementY = event.clientY - backupY;
				var dif = jQuery(window).height() - elementHeight;
				var elems = jQuery('.parallax_element');
				var firstTop = parseInt(elems[0].style.top.replace("px", ''));
				var topLimit = ((elems.length - 1) * elementHeight * -1) + dif;
				if(topFactor + movementY > 0){
					topFactor = 0;
					movementY = 0;
				}else if(topFactor + movementY < topLimit){
					movementY = topLimit - topFactor
				}
				jQuery.each(elems, function(index, value) {
					value.style.top = ((index * elementHeight) + topFactor + movementY) + 'px';
				});
				scrollTo(parseInt(elems[0].style.top.replace("px", '')) * -1);					
			}
		});
		jQuery('#parallax_container').bind('mouseup mouseout touchend', function(event){
			event.preventDefault();
			backupY = null;
			topFactor = null;
		});
	}else{
		jQuery(window).bind('scroll', scrollTo);
	}

	// adjust initial background positions
	scrollTo.call(this, 0);

	jQuery('#parallax_container').show();
}